package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class StatementItemServiceImpl implements IStatementItemService {
    @Autowired
    private StatementItemMapper statementItemMapper;
    @Autowired
    private StatementMapper statementMapper;


    @Override
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<StatementItem>(statementItemMapper.selectForList(qo));
    }


    @Override
    public void save(StatementItem statementItem) {
        // 从安全角度考虑，前台传递过来的对象是不可以直接使用的。
        // 所以我们都新建对象。这样无论如何都不会因为前台传递了默认值而改变我们的默认值数据。

        statementItemMapper.insert(statementItem);
    }

    @Override
    public StatementItem get(Long id) {
        return statementItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(StatementItem statementItem) {

        statementItemMapper.updateByPrimaryKey(statementItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            statementItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<StatementItem> list() {
        return statementItemMapper.selectAll();
    }

    @Override
    public void     saveItems(List<StatementItem> list) {
        //判断 集合
        if (list !=null && list.size()>0){
            //拿到优惠价格  集合的最后一个
            StatementItem temp = list.remove(list.size() - 1);
            //获取结算单 id    statementId
            Long statementId = temp.getStatementId();
            //获取优惠价格 discountAmount
            //必须处于 消费中 才能进行保存明细操作
            Statement statement = statementMapper.selectByPrimaryKey(statementId);
            if (Statement.STATUS_PAID.equals(statement.getStatus())){
                throw new BusinessException("已支付的结算单无法进行保存操作");
            }
            //保存操作
            //由于不确定之前是否存在数据,(是否是已近保存修改过的)  所以采用先删后加的操作
            statementItemMapper.delDetailedByStatementId(statement.getId());
            //保存结算单明细
            statementItemMapper.insertDetailedBatch(list);
            //首先 设置 总金额 totalAmount   总数量 totalQuantity 折扣金额 discountAmount
            BigDecimal totalAmount = new BigDecimal("0.00"); //总金额
            BigDecimal totalQuantity = new BigDecimal("0");  //总数量
            BigDecimal discountAmount = temp.getItemPrice();     //折扣金额
            //遍历集合 将数据保存进去
            for (StatementItem statementItem : list) {
                //计算  总金额
                totalAmount=totalAmount.add(statementItem.getItemPrice().multiply(statementItem.getItemQuantity()));
                //计算 总数量
                totalQuantity=totalQuantity.add(statementItem.getItemQuantity());
            }
            if (discountAmount == null || discountAmount.compareTo(new BigDecimal(0))<0){
                throw new BusinessException("优惠金额不能小于0");
            }
            if (discountAmount.compareTo(totalAmount) > 0){
                throw new BusinessException("优惠金额不能大于总金额");
            }
            //更新结算单信息
            statement.setTotalAmount(totalAmount);
            statement.setTotalQuantity(totalQuantity);
            statement.setDiscountAmount(discountAmount);
            statementMapper.updateDetailed(statement);
        }
    }

    @Override
    public Workbook export(Long statementId) {
        //定义工作表
        XSSFWorkbook wb =new XSSFWorkbook();
        //定义 sheet 页
        XSSFSheet sheet =wb.createSheet("结算单明细");
        //定义标题头
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("服务名称");
        row.createCell(1).setCellValue("服务价格");
        row.createCell(2).setCellValue("数量");
        //将数据写入workbook 中
        //第一行 是标题头 写入数据时要跳过第一行
        List<StatementItem> statementItemList = statementItemMapper.selectById(statementId);
        for (int i =0;i<statementItemList.size();i++){
            StatementItem statementItem = statementItemList.get(i);
            //第一行是标题头 跳过第一行
            Row row1 = sheet.createRow(i+1);
            row1.createCell(0).setCellValue(statementItem.getItemName());
            row1.createCell(1).setCellValue(statementItem.getItemPrice().doubleValue());
            row1.createCell(2).setCellValue( statementItem.getItemQuantity().doubleValue());
        }
        return wb;
    }
}
